<template>
  <div class="stacked-carousel-container">
    <div class="carousel-wrapper">

      <div class="stacked-cards">
        <div
          v-for="(book, index) in books"
          :key="book.bookId"
          class="stacked-card"
          :class="{
            'active': index === currentIndex,
            'prev': index < currentIndex,
            'next': index > currentIndex
          }"
          :style="getCardStyle(index)"
          @click="selectCard(index)"
        >
          <div class="book-stacked-card">
            <div class="book-cover-stacked">
              <img
                v-if="getBookImage(book)"
                :src="getBookImage(book)"
                :alt="book.bookName"
                :data-isbn="book.bookIsbn"
                class="book-image"
                @error="handleImageError"
              >
              <div v-else class="book-cover-placeholder">
                <div class="book-cover-icon">{{ getBookIcon(book) }}</div>
                <div class="book-cover-title">{{ book.bookName }}</div>
                <div class="book-cover-author">{{ book.bookAuthor }}</div>
                <div class="book-cover-category">{{ getBookCategory(book) }}</div>
              </div>
            </div>
            <div class="book-info-stacked">
              <h3 class="book-title">{{ book.bookName }}</h3>
              <p class="book-author">{{ book.bookAuthor }}</p>
              <p class="book-price">¥{{ book.bookPrice }}</p>
              <!-- 关键修改1：管理员隐藏借阅按钮 -->
              <div class="book-actions" v-if="!isAdmin">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="borrowBook(book)"
                  :disabled="book.bookStatus !== '0'"
                  class="borrow-btn-stacked"
                >
                  <el-icon v-if="book.bookStatus === '0'"><Reading /></el-icon>
                  <el-icon v-else><Star /></el-icon>
                  {{ book.bookStatus === '0' ? '借阅' : '已借阅' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>


    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ArrowLeft, ArrowRight, Reading, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  books: {
    type: Array,
    default: () => []
  },
  autoPlay: {
    type: Boolean,
    default: true
  },
  interval: {
    type: Number,
    default: 3000
  },
  // 关键修改2：接收父组件传递的管理员权限标识
  isAdmin: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['borrow-book'])

// 响应式数据
const currentIndex = ref(0)
const isTransitioning = ref(false)
const autoPlayTimer = ref(null)

// 计算属性
const totalBooks = computed(() => props.books.length)

// 方法：获取卡片样式
const getCardStyle = (index) => {
  const total = totalBooks.value
  if (total === 0) return { opacity: 0, transform: 'scale(0)', zIndex: 1 }

  // 计算相对于当前卡片的循环距离
  let diff = index - currentIndex.value
  // 处理循环：确保diff在[-total/2, total/2]范围内
  if (diff > total / 2) {
    diff -= total
  } else if (diff < -total / 2) {
    diff += total
  }

  const absDiff = Math.abs(diff)

  // 只显示最近的几张卡片
  if (absDiff > Math.min(3, Math.floor(total / 2))) {
    return {
      opacity: 0,
      transform: 'scale(0.5) translateY(100px)',
      zIndex: 1
    }
  }

  let transform = ''
  let zIndex = 20 - absDiff
  let opacity = 1

  if (diff === 0) {
    // 当前卡片 - 完全显示
    transform = 'scale(1) translateY(0) translateX(0)'
    zIndex = 20
    opacity = 1
  } else if (diff === -1 || diff === total - 1) {
    // 左侧第一张卡片（或最后一张卡片）
    transform = 'scale(0.9) translateY(20px) translateX(-100px)'
    zIndex = 19
    opacity = 0.8
  } else if (diff === 1 || diff === -(total - 1)) {
    // 右侧第一张卡片（或第一张卡片）
    transform = 'scale(0.9) translateY(20px) translateX(100px)'
    zIndex = 19
    opacity = 0.8
  } else if (diff === -2 || diff === total - 2) {
    // 左侧第二张卡片
    transform = 'scale(0.8) translateY(40px) translateX(-200px)'
    zIndex = 18
    opacity = 0.6
  } else if (diff === 2 || diff === -(total - 2)) {
    // 右侧第二张卡片
    transform = 'scale(0.8) translateY(40px) translateX(200px)'
    zIndex = 18
    opacity = 0.6
  } else if (diff === -3 || diff === total - 3) {
    // 左侧第三张卡片
    transform = 'scale(0.7) translateY(60px) translateX(-300px)'
    zIndex = 17
    opacity = 0.4
  } else if (diff === 3 || diff === -(total - 3)) {
    // 右侧第三张卡片
    transform = 'scale(0.7) translateY(60px) translateX(300px)'
    zIndex = 17
    opacity = 0.4
  }

  return {
    transform,
    zIndex,
    opacity
  }
}

// 选择卡片
const selectCard = (index) => {
  if (isTransitioning.value || index === currentIndex.value) return

  isTransitioning.value = true
  currentIndex.value = index

  setTimeout(() => {
    isTransitioning.value = false
  }, 300)
}

// 下一张卡片
const nextBook = () => {
  if (isTransitioning.value) return

  isTransitioning.value = true
  currentIndex.value = (currentIndex.value + 1) % totalBooks.value

  setTimeout(() => {
    isTransitioning.value = false
  }, 300)
}

// 上一张卡片
const prevBook = () => {
  if (isTransitioning.value) return

  isTransitioning.value = true
  currentIndex.value = (currentIndex.value - 1 + totalBooks.value) % totalBooks.value

  setTimeout(() => {
    isTransitioning.value = false
  }, 300)
}

// 借阅图书（管理员拦截）
const borrowBook = (book) => {
  // 关键修改3：管理员调用借阅时拦截
  if (props.isAdmin) {
    ElMessage.error('管理员无借阅权限')
    return
  }
  emit('borrow-book', book)
}

// 获取图书图片（修复路径问题）
const getBookImage = (book) => {
  if (book.bookImage) {
    // Base64格式直接返回
    if (book.bookImage.startsWith('data:image/')) {
      return book.bookImage
    }
    // URL格式校验（排除无效链接）
    if (book.bookImage.startsWith('http://') || book.bookImage.startsWith('https://')) {
      // 过滤openlibrary等可能失效的链接
      if (book.bookImage.includes('covers.openlibrary.org')) {
        return null
      }
      return book.bookImage
    }
  }
  // 无有效图片时返回null（使用占位符）
  return null
}

// 关键修改4：修复图片错误处理（避免路径错误）
const handleImageError = (event) => {
  const img = event.target
  const isbn = img.dataset.isbn
  // 优先使用ISBN尝试豆瓣图片（兼容之前逻辑）
  if (isbn) {
    img.src = `https://img1.doubanio.com/view/subject/s/public/s${isbn}.jpg`
    // 二次错误则使用本地占位图（需确保占位图路径正确）
    img.onerror = () => {
      img.src = '/src/assets/covers/placeholder.svg'
    }
  } else {
    // 无ISBN时直接使用本地占位图
    img.src = '/src/assets/covers/placeholder.svg'
  }
}

// 获取图书图标
const getBookIcon = (book) => {
  const title = book.bookName.toLowerCase()
  const author = book.bookAuthor.toLowerCase()

  if (title.includes('java') || title.includes('spring') || title.includes('编程') || title.includes('开发')) return '💻'
  if (title.includes('小说') || title.includes('文学') || author.includes('村上') || author.includes('东野')) return '📖'
  if (title.includes('历史') || title.includes('传记')) return '📜'
  if (title.includes('科学') || title.includes('技术')) return '🔬'
  if (title.includes('艺术') || title.includes('设计')) return '🎨'
  if (title.includes('哲学') || title.includes('思想')) return '🤔'
  if (title.includes('经济') || title.includes('管理')) return '💰'
  if (title.includes('教育') || title.includes('学习')) return '🎓'
  if (title.includes('健康') || title.includes('医学')) return '🏥'
  if (title.includes('旅游') || title.includes('地理')) return '🗺️'
  if (title.includes('美食') || title.includes('烹饪')) return '🍳'
  if (title.includes('运动') || title.includes('健身')) return '🏃'
  if (title.includes('音乐') || title.includes('歌曲')) return '🎵'
  if (title.includes('电影') || title.includes('影视')) return '🎬'
  if (title.includes('心理学') || title.includes('心理')) return '🧠'
  if (title.includes('法律') || title.includes('法规')) return '⚖️'
  if (title.includes('建筑') || title.includes('工程')) return '🏗️'
  if (title.includes('农业') || title.includes('种植')) return '🌾'
  if (title.includes('环境') || title.includes('生态')) return '🌱'
  return '📚'
}

// 获取图书分类
const getBookCategory = (book) => {
  const title = book.bookName.toLowerCase()
  const author = book.bookAuthor.toLowerCase()

  if (title.includes('java') || title.includes('spring') || title.includes('编程')) return '技术编程'
  if (title.includes('小说') || title.includes('文学') || author.includes('村上') || author.includes('东野')) return '文学小说'
  if (title.includes('历史') || title.includes('传记')) return '历史传记'
  if (title.includes('科学') || title.includes('技术')) return '科学技术'
  if (title.includes('艺术') || title.includes('设计')) return '艺术设计'
  if (title.includes('哲学') || title.includes('思想')) return '哲学思想'
  if (title.includes('经济') || title.includes('管理')) return '经济管理'
  if (title.includes('教育') || title.includes('学习')) return '教育学习'
  return '综合图书'
}

// 自动播放控制
const startAutoPlay = () => {
  if (!props.autoPlay || totalBooks.value <= 1) return

  autoPlayTimer.value = setInterval(() => {
    nextBook()
  }, props.interval)
}

const stopAutoPlay = () => {
  if (autoPlayTimer.value) {
    clearInterval(autoPlayTimer.value)
    autoPlayTimer.value = null
  }
}

// 监听书籍数据变化
watch(() => props.books, (newBooks) => {
  if (newBooks.length > 0) {
    currentIndex.value = 0
    startAutoPlay()
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  if (totalBooks.value > 0) {
    startAutoPlay()
  }
})

onUnmounted(() => {
  stopAutoPlay()
})
</script>

<style scoped>
.stacked-carousel-container {
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 30px;
  overflow: visible;
  position: relative;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.carousel-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.stacked-cards {
  position: relative;
  width: 450px;
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
  perspective: 1000px;
  overflow: visible;
}

.stacked-card {
  position: absolute;
  width: 100%;
  height: 100%;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  transform-origin: center center;
}

.stacked-card.prev,
.stacked-card.next {
  pointer-events: auto;
}

.book-stacked-card {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.8));
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(102, 126, 234, 0.2);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border: 1px solid rgba(102, 126, 234, 0.1);
  backdrop-filter: blur(10px);
}

.book-cover-stacked {
  width: 100%;
  height: 70%;
  position: relative;
  overflow: hidden;
}

.book-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.book-cover-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #ff6b6b 0%, #4ecdc4 50%, #45b7d1 100%);
  border: 2px solid #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 6px 20px rgba(0,0,0,0.15);
}

.book-cover-placeholder::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: shimmer 3s ease-in-out infinite;
}

@keyframes shimmer {
  0%, 100% { transform: rotate(0deg); }
  50% { transform: rotate(180deg); }
}

.book-cover-icon {
  font-size: 3em;
  margin-bottom: 8px;
  z-index: 2;
  position: relative;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}

/* 关键修改5：补充 line-clamp 标准属性，解决兼容性警告 */
.book-cover-title {
  font-size: 1.1em;
  font-weight: bold;
  margin-bottom: 4px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.4);
  z-index: 2;
  position: relative;
  padding: 0 8px;
  line-height: 1.3;
  max-height: 2.6em;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2; /* 标准属性，解决兼容性警告 */
  -webkit-box-orient: vertical;
  box-orient: vertical; /* 标准属性，解决兼容性警告 */
}

.book-cover-author {
  font-size: 0.8em;
  opacity: 0.95;
  text-shadow: 0 1px 3px rgba(0,0,0,0.4);
  z-index: 2;
  position: relative;
  margin-bottom: 8px;
  max-width: 90%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-cover-category {
  font-size: 0.7em;
  opacity: 0.8;
  background: rgba(255,255,255,0.2);
  padding: 2px 8px;
  border-radius: 12px;
  z-index: 2;
  position: relative;
  backdrop-filter: blur(10px);
}

.book-info-stacked {
  padding: 25px;
  height: 30%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  border-top: 1px solid rgba(102, 126, 234, 0.1);
}

.book-title {
  font-size: 20px;
  font-weight: 700;
  background: linear-gradient(135deg, #2c3e50, #667eea);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 0 10px 0;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-author {
  font-size: 15px;
  color: #667eea;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
}

.book-price {
  font-size: 18px;
  font-weight: 700;
  background: linear-gradient(135deg, #e74c3c, #f39c12);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 0 15px 0;
}

.book-actions {
  display: flex;
  justify-content: center;
}

.borrow-btn-stacked {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 25px;
  padding: 12px 25px;
  font-weight: 600;
  font-size: 15px;
  color: white;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  gap: 8px;
  position: relative;
  overflow: hidden;
}

.borrow-btn-stacked::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.borrow-btn-stacked:hover::before {
  left: 100%;
}

.borrow-btn-stacked:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.4);
}

.borrow-btn-stacked:disabled {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4px 15px rgba(149, 165, 166, 0.3);
}

.borrow-btn-stacked .el-icon {
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stacked-cards {
    width: 380px;
    height: 500px;
  }

  .book-title {
    font-size: 16px;
  }

  .book-author {
    font-size: 12px;
  }

  .book-price {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .stacked-cards {
    width: 320px;
    height: 420px;
  }

  .book-title {
    font-size: 14px;
  }

  .book-author {
    font-size: 11px;
  }

  .book-price {
    font-size: 12px;
  }
}
</style>